<template>
    <div class="add_edit edit_article">
        <div class="add_field">
            <div class="field_list article_title">
                <span class="mandatory_logo">*</span>
                <span class="search_text">文章标题：</span>
                <el-input v-model="edit_article_title" placeholder="请输入文章标题，限64个汉字" maxlength="64" show-word-limit></el-input>
            </div>
            <div class="field_list product_info">
                <div class="project">
                    <span class="search_text">项目：</span>
                    <el-select v-model="edit_project" multiple filterable collapse-tags placeholder="请选择项目">
                        <el-option
                            v-for="item in project_list"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </div>
                <div class="article_author">
                    <span class="search_text">作者信息：</span>
                    <div class="author_info">
                        <el-input v-model="edit_author_name" placeholder="请输入作者姓名" maxlength="64"></el-input>
                        <el-input v-model="edit_institutions_name" placeholder="请输入机构名称" maxlength="64"></el-input>
                    </div>
                </div>
            </div>
            <div class="field_list desc">
                <span class="search_text">描述：</span>
                <el-input
                    type="textarea"
                    placeholder="请填写文章摘要描述，限200个汉字"
                    v-model="edit_remark"
                    maxlength="200"
                    show-word-limit>
                </el-input>
            </div>
        </div>
        <div class="content">
            <div class="text">
                <span class="mandatory_logo">*</span>
                <span class="search_text">文章内容：</span>
            </div>
            <div class="field_list article_content" ref="editor">
                <!-- @input="newContent" -->
                <editor v-model="edit_article_content"/>
            </div>
        </div>
        <div class="image">
            <div class="field_list article_image">
                <span class="search_text">缩略图：</span>
                <img class="promit" src="../../assets/common/promit.svg" alt="">
                <span class="upload_promit">请上传 200 x 150 大小的图片用于列表显示，不超过512K，支持jpg、jpeg、png格式。</span>
                <el-form :model="dataEditForm" ref="dataForm">
                    <el-form-item :class="{hide:hideEditUpload}">
                        <el-upload
                            ref="upload"
                            action="#"
                            :file-list="dataEditForm.imgFileList"
                            list-type="picture-card"
                            :on-change="OnChangeEditUpload"
                            :on-preview="handleEditImg"
                            :on-exceed="handleExceedEditImg"
                            :on-remove="handleRemoveEditImg"
                            accept="image/jpeg,image/png,image/jpg,"
                            :auto-upload="false"
                            :limit="1">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisibleEditImg" append-to-body>
                            <img width="100%" :src="dialogEditImageUrl" alt="">
                        </el-dialog>
                    </el-form-item>
                </el-form>
            </div>
            <div class="field_list article_status">
                <span class="search_text">文章状态：</span>
                <el-select v-model="edit_article_status" placeholder="请选择状态">
                    <el-option
                        v-for="item in article_status_list"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                </el-select>
            </div>
        </div>
        <div class="submit_btn">
            <el-button @click="cancel_save_data">取消</el-button>
            <el-button type="primary" @click="edit_article_info">确定</el-button>
        </div>
        <el-dialog
            title="提示"
            :visible.sync="dialogVisibleSave"
            width="420px"
            class="save"
            :close-on-click-modal="false">
            <span>{{save_promit_title}}</span>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogVisibleSave = false">确定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="420px"
            class="cancel_save"
            :close-on-click-modal="false">
            <span>现在取消内容将不会被保存，确定取消吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelEditDialog">确定</el-button>
                <el-button type="primary" @click="dialogVisible = false">返回</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { api, baseAjax } from '../../api/api';
    import {statusCode} from '../../utils/index';
    import editor from '../../components/tinymce/index';
    import Cookies from 'js-cookie';
    import {httpFormUpload} from '../../api/http';
    import bus from '../../assets/js/eventBus';
    export default {
        name: "editArticleManagement",
        data() {
            return {
                dialogVisible:false,
                dialogVisibleSave:false,
                save_promit_title:'',
                project_list:[],  //项目下拉框值
                article_status_list:[   //文章状态下拉框值
                    {
                        id:0,
                        name:'停用'
                    },
                    {
                        id:1,
                        name:'发布'
                    }
                ],
                edit_article_id:null,
                edit_article_title:'',  //编辑文章标题
                edit_article_content:'',  //编辑文章内容
                edit_project:[],   //编辑项目
                edit_author_name:'',   //编辑作者姓名
                edit_institutions_name:'',   //编辑机构名称
                edit_remark:'',   //编辑描述
                edit_article_status:1,  //编辑文章状态
                dataEditForm: {   //上传图片
                    imgFileList: []
                },
                hideEditUpload:false,   //是否显示编辑图片加号
                dialogVisibleEditImg:false,   //是否查看编辑缩略图
                dialogEditImageUrl:'',  //编辑缩略图url
                user_info:{}
            }
        },
        components:{
            editor
        },
        mounted(){
            this.user_info = JSON.parse(this.EncryUtil.decryptByAES(Cookies.get('user_info')));
            this.getProductList();//获取产品
            this.getArticleInfo();//获取文章信息
        },
        methods: {
            //编辑图片验证
            OnChangeEditUpload(file, fileList){
                let isType = false;
                if(file.raw.type === 'image/jpeg'){
                    isType = true;
                }else if(file.raw.type === 'image/jpg'){
                    isType = true;
                }else if(file.raw.type === 'image/png'){
                    isType = true;
                }
                const isLt5 = file.size / 1024 < 512;
                if (isType != true) {
                    this.dialogVisibleSave = true;
                    this.save_promit_title = '上传的缩略图只能是 JPG、jpeg、png 格式!';
                    fileList.pop();
                }else if (!isLt5) {
                    this.dialogVisibleSave = true;
                    this.save_promit_title = '上传的缩略图大小不能超过 512k!';
                    fileList.pop();
                } else {
                    this.dataEditForm.imgFileList.push(file);
                }
                this.hideEditUpload = fileList.length == 1;
            },
            //查看编辑缩略图
            handleEditImg(file){
                this.dialogVisibleEditImg = true;
                this.dialogEditImageUrl = file.url;
            },
            //编辑上传缩略图验证提示
            handleExceedEditImg(){
                this.dialogVisibleSave = true;
                this.save_promit_title = '只能上传1张图片';
            },
            //删除编辑缩略图
            handleRemoveEditImg(){
                this.dataEditForm.imgFileList = [];
                this.dialogVisibleEditImg = false;
                this.dialogEditImageUrl = '';
                this.hideEditUpload = false;
            },

            //获取文章信息
            getArticleInfo(){
                let article_info = JSON.parse(this.EncryUtil.decryptByAES(Cookies.get('article_info')));
                let productId = [];
                let articleStatus = null;
                if((article_info.productId && article_info.productId.length == 1 && article_info.productId[0] == 0) || article_info.productId == null){
                    productId = [];
                }else{
                    article_info.productId.forEach(item=>{
                        productId.push(Number(item))
                    });
                }
                this.edit_article_id = article_info.articleId;
                this.edit_article_title = article_info.articleTitle;
                this.edit_article_content = article_info.articleContent;
                this.edit_project = productId;
                this.edit_author_name = article_info.authorName;
                this.edit_institutions_name = article_info.authorInstitution;
                this.edit_remark = article_info.description;
                if(article_info.articleImg){
                    this.dataEditForm.imgFileList.push({
                        url:article_info.articleImg.replace('["', '').replace('"]', '')
                    });
                }
                this.article_status_list.forEach(val=>{
                    if(article_info.articleStatus === val.name){
                        articleStatus = val.id
                    }
                });
                this.edit_article_status = articleStatus;
            },
            //显示取消弹框
            cancel_save_data(){
                if(this.edit_article_title || this.edit_article_content || this.edit_project.length != 0 || this.edit_author_name || this.edit_institutions_name || this.edit_remark || this.dataEditForm.imgFileList.length != 0){
                    this.dialogVisible = true;
                }else{
                    this.$router.go(-1);
                }
            },
            //取消编辑弹框
            cancelEditDialog(){
                this.dialogVisible = false;
                this.$router.go(-1);
                this.edit_article_id = null;
                this.edit_article_title = '';
                this.edit_article_content = '';
                this.edit_project = [];
                this.edit_author_name = '';
                this.edit_institutions_name = '';
                this.edit_remark = '';
                this.edit_article_status = 1;
                this.dataEditForm.imgFileList = [];
                this.dialogVisibleEditImg = false;
                this.dialogEditImageUrl = '';
                this.hideEditUpload = false;
            },
            //编辑文章信息
            edit_article_info(){
                let that = this;
                let article_title = this.edit_article_title.trim();
                let article_content = this.edit_article_content.replace(/[]|[&nbsp;]|[<p>,</p>]/g, '').trim();
                if(!article_title){
                    this.dialogVisibleSave = true;
                    this.save_promit_title = '请填写"文章标题"';
                }else if(article_title.length > 64){
                    this.dialogVisibleSave = true;
                    this.save_promit_title = '文章标题不能超过64个字';
                }else if(!article_content){
                    this.dialogVisibleSave = true;
                    this.save_promit_title = '请填写文章内容';
                }else{
                    let product_list = [];
                    if(this.edit_project.length){
                        this.edit_project.forEach(item=>{
                            that.project_list.forEach(val=>{
                                if(item == val.id){
                                    product_list.push({
                                        id:val.id,
                                        name:val.name
                                    });
                                }
                            });
                        });
                    }else{
                        product_list.push({
                            id:0,
                            name:''
                        });
                    }
                    let obj = {
                        createRepId:this.user_info.repId,
                        createRepName:this.user_info.name,
                        articleTitle:article_title,
                        articleContent:this.edit_article_content,
                        authorName:this.edit_author_name,
                        authorInstitution:this.edit_institutions_name,
                        description:this.edit_remark,
                        articleStatus:this.edit_article_status,
                        productList:product_list,
                        id:this.edit_article_id
                    };

                    let regLeft = new RegExp("\\[",'g');
                    let regRight = new RegExp('\\]', 'g');

                    if(this.dataEditForm.imgFileList.length === 1 && this.dataEditForm.imgFileList[0].status == 'success'){
                        obj.articleImg = this.dataEditForm.imgFileList[0].url;
                    }
                    let data = {
                        updateArticleParam:JSON.stringify(obj).replace(regLeft, '%5B').replace(regRight, '%5D')
                    };
                    let formData = new FormData();
                    if(this.dataEditForm.imgFileList.length === 1 && this.dataEditForm.imgFileList[0].status == 'ready'){
                        formData.append('articleImg', this.dataEditForm.imgFileList[0].raw);
                    }
                    httpFormUpload(api.edit_article_info_url, data, formData, (res)=>{
                        if(res.data.code === statusCode.success){
                            if(res.data.data == true){
                                that.$router.go(-1);
                                that.$message.success('文章编辑成功');
                            }else{
                                that.$message.error('文章编辑失败');
                            }
                            that.edit_article_id = null;
                            that.edit_article_title = '';
                            that.edit_article_content = '';
                            that.edit_project = [];
                            that.edit_author_name = '';
                            that.edit_institutions_name = '';
                            that.edit_remark = '';
                            that.edit_article_status = 1;
                            that.dataEditForm.imgFileList = [];
                            that.dialogVisibleEditImg = false;
                            that.dialogEditImageUrl = '';
                            that.hideEditUpload = false;
                        }
                    });
                }
            },
            //获取所有产品
            getProductList(){
                let that = this;
                baseAjax(api.get_all_product, '', (res)=>{
                    if(res.code === statusCode.success){
                        that.project_list = res.data;
                    }
                });
            }
        }
    }
</script>

<style lang="less" scoped>
.edit_article{
    .add_field{
        .article_title{
            .el-input{
                margin-left:10px;
            }
        }
        .product_info{
            margin-left:10px;
            .project{
                width:38%;
            }
            .article_author{
                width:59%;
                .author_info{
                    display:flex;
                    div:first-child{
                        margin-right:10px;
                        width:50%;
                    }
                }
            }
        }
        .desc{
            margin-left:10px;
        }
    }
    .image{
      padding:24px 0 24px 32px;
      box-sizing:border-box;
      .article_status{
        /deep/.el-select{
          display:block;
          width: 23%;
          .el-input{
            .el-input__inner{
              height: 32px;
              background-color: #FFFFFF;
              border-radius: 2px;
              border: 1px solid #DDDFE6;
            }
            .el-input__suffix{
              .el-input__suffix-inner{
                .el-input__icon{
                  line-height:32px;
                }
              }
            }
          }
        }
      }
    }
    .save{
        .el-dialog{
            .el-dialog__footer{
                .dialog-footer{
                    .el-button:hover{
                        color:#fff;
                    }
                }
            }
        }
    }
}
</style>
